import { Avatar, Button, Checkbox, Dropdown, Flex, Form, Input, message, Modal, Radio, Select, Space, type FormProps } from "antd"
import type { CheckboxGroupProps } from "antd/es/checkbox"
import { useForm } from "antd/es/form/Form"

import { useMemo, useState, type ReactNode } from "react"

import { reqGetCaptcha } from "../../api/captchaApi"
import { reqCheckPass, reqLogin, reqRegister, reqUpdatePass } from "../../api/userApi"
import type { userData } from "../../api/type/userType"
import type { ROOTSTATE } from "../../Store"
import { useDispatch, useSelector } from "react-redux"
import { login, logout } from "../../Store/userSlice"
import { Link, NavLink, useNavigate } from "react-router"


const styleBox: React.CSSProperties = {
    height: 100,
    backgroundColor: "#001e2e",
}
const styleContent: React.CSSProperties = {
    width: 1200,
    height: 100,
    margin: "0 auto",
    justifyContent: "space-around"
}
export const Header = () => {
    type loginForm = {
        username1: string;
        password1: string;
        code1: string;
        noLogin: boolean;
    };
    type registerForm = {
        username2: string;
        nickname?: string;
        code2: string;
    };
    type passForm = {
        confirmPass: string
    }
    const [messageApi, contextHolder] = message.useMessage();

    const success = (msg: string) => {
        messageApi.open({
            type: 'success',
            content: msg,
        });
    };
    const error = (msg: string) => {
        messageApi.open({
            type: 'error',
            content: msg,
        });
    };

    const onLoginFinish: FormProps<loginForm>['onFinish'] = async (values) => {
        const result = await reqLogin({
            username: values.username1,
            password: values.password1,
            code: values.code1,
            noLogin: values.noLogin
        })
        if (result.code == 1) {
            error(result.msg);
            getCode();
        } else {
            if (result.token) {
                if (values.noLogin) {
                    localStorage.setItem("token", result.token);
                } else {
                    sessionStorage.setItem("token", result.token);
                }
                dispatch(login(result.data!))
                success(result.msg);
                setOpen(false);
            }

        }

    };
    const onRegisterFinish: FormProps<registerForm>['onFinish'] = async (values) => {
        console.log('Success:', values);
        const { code, msg } = await reqRegister({
            username: values.username2,
            nickname: values.nickname,
            code: values.code2
        })
        if (code === 0) {
            success("注册成功,请登录")
            from1.resetFields();
            setType("login")
        } else {
            error(msg)
            getCode();
        }

    };





    const [open, setOpen] = useState(false)
    const options: CheckboxGroupProps<string>['options'] = [
        { label: '登录', value: 'login' },
        { label: '注册', value: 'register' }
    ];
    const [type, setType] = useState<"login" | "register">("login")
    const [codeHTML, setCodeHTML] = useState("")

    const { user, isLogin } = useSelector((state: ROOTSTATE) => state.userStore);
    const dispatch = useDispatch();

    //退出登录
    const Logout = () => {
        dispatch(logout());
        localStorage.removeItem("token");
        sessionStorage.removeItem("token");
    }
    const onPassFinish: FormProps<passForm>['onFinish'] = async (values) => {
        console.log('Success:', values);
        const newUser = await reqUpdatePass(user.username!, values.confirmPass);
        if (newUser != null) {
            //重置表单内容
            fromPass.resetFields();
            //退出修改密码的窗口
            setOpenPass(false);
            //退出登录
            Logout()
            //成功提示
            success("修改密码成功")
        }
    }

    const [value,setValue] = useState("")
    const [searchType,setSearchType] = useState("issue")
    const navigate = useNavigate()
    const searchFn = ()=>{
        if(value === ""){
            navigate("/issue")
        }else{
            navigate(`/search?type=${searchType}&value=${value}`)
        }
    }

    //控制修改密码对话框
    const [openPass, setOpenPass] = useState(false)

    //拿到form实例,用来在点击重置按钮的时候调用实例的resetFields()方法重置表单内容
    let [from1] = useForm();
    let [fromPass] = useForm();
    let form: ReactNode;
    form = useMemo(() => {
        if (type === "login") {
            return <Form labelCol={{ span: 5 }} onFinish={onLoginFinish} initialValues={{ noLogin: true }} form={from1}>
                <Form.Item
                    label="用户名"
                    name="username1"
                    rules={[{ required: true, message: '请输入用户名' }]}>
                    <Input />
                </Form.Item>
                <Form.Item
                    label="密码"
                    name="password1"
                    rules={[{ required: true, message: '请输入密码' }]}>
                    <Input />
                </Form.Item>
                <Form.Item
                    label="验证码"
                    name="code1"
                    rules={[{ required: true, message: '请输入验证码' }]}>
                    <Flex gap={20} align="flex-start">
                        <Input />
                        <div dangerouslySetInnerHTML={{ __html: codeHTML }}
                            style={{ width: 150, height: 50 }} onClick={()=>{getCode()}}></div>
                    </Flex>
                </Form.Item>
                <Form.Item
                    label={null}
                    name="noLogin"
                    valuePropName="checked">
                    <Checkbox>30天免登录</Checkbox>
                </Form.Item>
                <Form.Item label={null} >
                    <Flex gap={40}>
                        <Button type="primary" htmlType="submit">
                            登录
                        </Button>
                        <Button onClick={() => from1.resetFields()}>
                            重置
                        </Button>
                    </Flex>
                </Form.Item>
            </Form>
        } else if (type === "register") {
            return <>

                <Form labelCol={{ span: 5 }} onFinish={onRegisterFinish} initialValues={{ noLogin: true }} form={from1}>
                    <Form.Item
                        label="用户名"
                        name="username2"
                        rules={[{ required: true, message: '请输入用户名' }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="昵称"
                        name="nickname">
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="验证码"
                        name="code2"
                        rules={[{ required: true, message: '请输入验证码' }]}>
                        <Flex gap={20} align="flex-start">
                            <Input />
                            <div dangerouslySetInnerHTML={{ __html: codeHTML }}
                                style={{ width: 200, height: 50 }} onClick={()=>{getCode()}}></div>
                        </Flex>
                    </Form.Item>
                    <Form.Item label={null} >
                        <Flex gap={40}>
                            <Button type="primary" htmlType="submit" >
                                注册
                            </Button>
                            <Button onClick={() => from1.resetFields()}>
                                重置
                            </Button>
                        </Flex>
                    </Form.Item>
                </Form>
            </>
        }
    }, [type, codeHTML])
    //获取验证码的方法
    const getCode = async () => {
        const { data } = await reqGetCaptcha() //Promise对象 {status:状态,value:值}
        setCodeHTML(data)
    }
    return (
        <>
            {contextHolder}
            <Flex style={styleBox}>
                <Flex style={styleContent} align="center">
                    <Flex><span style={{ fontSize: 40, fontWeight: "bold", color: "white" }}>shn</span><span style={{ fontSize: 40, fontWeight: "bold", color: "#1677FF" }}>station</span></Flex>
                    <Flex>
                        <NavLink to="/issue"><Button type="link">问答</Button></NavLink>
                        <NavLink to="/book"><Button type="link">书籍</Button></NavLink>
                        <NavLink to="/qa"><Button type="link">面试题</Button></NavLink>
                        <a href="https://www.niaodi.cn/" target="_blank"><Button type="link">在线课程</Button></a>
                    </Flex>
                    <Flex>
                        <Space.Compact>
                            <Select
                                defaultValue={searchType}
                                style={{ width: 100 }}
                                options={[
                                    { value: 'issue', label: '问答' },
                                    { value: 'book', label: '书籍' }
                                ]}
                                onChange={(e)=>setSearchType(e)}
                            />
                            <Input style={{ width: '60%' }} onChange={(e)=>{setValue(e.target.value)}}/>
                            <Button type="primary" onClick={searchFn}>搜索</Button>
                        </Space.Compact>
                    </Flex>
                    <Flex>
                        {!isLogin ?
                            <Button type="primary" onClick={() => {
                                setOpen(true);
                                getCode();
                            }}>登录/注册</Button>
                            :
                            <Dropdown menu={{
                                items: [{ key: 1, label: <Link to="/home">个人主页</Link>, disabled: false }, {
                                    key: 2, label: <div onClick={() => {
                                        setOpenPass(true)
                                    }} >修改密码</div>, disabled: false
                                }, { key: 3, label: <div>我的评论</div>, disabled: true }, { key: 4, label: <div>我的问题</div>, disabled: true },{key: 5, label: <div onClick={()=>{
                                    Logout()
                                    success("退出登录")
                                }}>退出登录</div>}]
                            }}>
                                <Avatar size={64} src={user.avatar} style={{ backgroundColor: "white" }} />
                            </Dropdown>
                        }
                    </Flex>
                </Flex>
            </Flex>

            <Modal
                title="登录/注册"
                open={open}
                footer={null}
                onCancel={() => { setOpen(false) }}
                width={500}
            >
                <Radio.Group
                    block
                    options={options}
                    defaultValue={"login"}
                    value={type}
                    optionType="button"
                    buttonStyle="solid"
                    onChange={(e) => {
                        setType(e.target.value)
                        getCode();
                    }}
                    style={{ marginBottom: 30 }}
                />
                {form}
            </Modal>

            
            <Modal title="修改密码" open={openPass} footer={null} onCancel={() => { setOpenPass(false) }}>
                <Form onFinish={onPassFinish} form={fromPass} labelCol={{ span: 5 }}>
                    <Form.Item label="原密码"
                        name="oldPass"
                        rules={[{
                            validator: async (_, value: string) => {
                                //发出请求
                                const { code } = await reqCheckPass(user.username!, value);
                                if (code != 0) {
                                    throw new Error("原始密码不正确")
                                }
                            }
                        }]}
                        validateDebounce={1000}>
                        <Input.Password></Input.Password>
                    </Form.Item>

                    <Form.Item label="新密码"
                        name="newPass"
                        rules={[{ required: true, message: '请输入新密码' }, { pattern: /^[0-9a-zA-Z@$]+$/g, message: "密码只能由数字字母@$组成" }, { max: 10, min: 3, message: "密码只能在3-10位" }]}
                        validateDebounce={1000}>
                        <Input.Password></Input.Password>
                    </Form.Item>

                    <Form.Item
                        label="确认密码"
                        name="confirmPass"
                        dependencies={['newPass']}
                        rules={[
                            {
                                required: true,
                            },
                            ({ getFieldValue }) => ({
                                validator(_, value) {
                                    if (!value || getFieldValue('newPass') === value) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('与新密码不一致'));
                                },
                            }),
                        ]} validateDebounce={1000}
                    ><Input.Password></Input.Password></Form.Item>

                    <Form.Item label={null} >
                        <Flex gap={40}>
                            <Button type="primary" htmlType="submit" >
                                确认
                            </Button>
                            <Button onClick={() => fromPass.resetFields()}>
                                重置
                            </Button>
                        </Flex>
                    </Form.Item>

                </Form>
            </Modal>
        </>
    )
}


